package com.g2room.driving.generate.kc890;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.g2room.driving.model.po.Category;
import com.g2room.driving.util.DbUtil;
import com.g2room.driving.util.EmailUtil;
import com.g2room.driving.util.FtpUtil;
import com.g2room.driving.util.HtmlUtil;

/**
 * 预发布文章，从文章抓取表拉到文章表，同时设置状态为已预发布
 * @author 高绪国
 *
 */
public class PrereleaKc890Article {
	
	/**
	 * 获取预发布文章
	 * @return
	 */
	public static void releaseArticle() {
		StringBuffer html = new StringBuffer();
		Map<Long, Category> categories = ReleaseKc890Article.getTypes();
		int pageSize = 2; 
		String totalIds = "";
		// 处理安全驾驶和驾驶技巧类别
		for(Long cid : categories.keySet()) {
			Category category = categories.get(cid);
			Random random = new Random();
			pageSize = random.nextInt(pageSize)%(pageSize) + 1;
			
			try {
				Thread.sleep(10);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			List<Long> articleList = null;
			// 只取一级分类 
			if(0 == category.getParentId()) {
				articleList = getIdsByCategoryId(category.getId());
			}
			if(null == articleList || articleList.isEmpty()) continue;
			String ids = randomIds(articleList, pageSize);
			totalIds += ids + ",";
			// 更新为已预发布
			updateState(ids);
			// 关闭连接
			DbUtil.closeConn();
			System.out.println("预发布类别=" + category.getName() + "，记录数=" + articleList.size() + ",ids=" + ids);
			html.append("&emsp;&emsp;类别=" + category.getName() + "，总记录数=" + articleList.size() + "，本次发布文章ID：" + ids + "<br>");
		}
		System.out.println("所有文章ID：" + totalIds);
		// 生成页面
		ReleaseKc890Article.createHtml();
//		System.out.println("关闭数据库连接。" );
		DbUtil.closeConn();
//		System.out.println("开始上传KC890到FTP上！");
//		// 上传到ftp
		//new FtpUtil().uploadHtmls(ReleaseKc890Article.publishHtmlPath, 1);
//		FtpUtil.uploadHtmls(GenerateKc890.publishHtmlPath);
//		QiniuFileOp.uploadDir(ReleaseKc890Article.publishHtmlPath, "kc890");
		System.out.println("开始发送邮件！");
		// 设置发件人地址、收件人地址和邮件标题
		EmailUtil cn = new EmailUtil();
		cn.sendHtmlMail("kc890发布邮件", "本次发布文章（" + totalIds.split(",").length + "）：<br><br>" + html.toString() + "<br><br>" + totalIds);
		System.out.println("发送邮件完成！");
	}
	
	public static List<Long> getIdsByCategoryId(long categoryId) {
		List<Long> articleIds = new ArrayList<Long>();
		try {
			Connection connection = DbUtil.getConn();
			Statement statement = connection.createStatement();
			String sql = "select id from d_article_kc890 where state=0 and category_id=" + categoryId;
			ResultSet rs = statement.executeQuery(sql);
			while (rs.next()) {
				articleIds.add(rs.getLong("id"));
			}
			rs.close();
			statement.close();
		} catch (Exception e) {
			e.printStackTrace();
			// 关闭连接
			DbUtil.closeConn();
		}
		return articleIds;
	}
	
	public static void updateState(String ids) {
		try {
			Connection connection = DbUtil.getConn();
			Statement statement = connection.createStatement();
			String sql = "update d_article_kc890 set state=1,publish_time='"+ HtmlUtil.date2String(new Date(), "yyyy-MM-dd hh:mm:ss")+"' where id in ("+ids+")";
			statement.execute(sql);
			statement.close();
			
		} catch(Exception e) {
			e.printStackTrace();
			// 关闭连接
			DbUtil.closeConn();
		}
	}

    // 从List中随机出count个对象  
    private static String randomIds(List<Long> list, int count) {
    	count = count >= list.size() ? list.size() : count;
        // 创建一个长度为count(count<=list)的数组,用于存随机数  
        int[] a = new int[count];  
        // 利于此数组产生随机数  
        int[] b = new int[list.size()];  
        int size = list.size();  
      
        // 取样填充至数组a满  
        for (int i = 0; i < count; i++) {  
            int num = (int) (Math.random() * size); // [0,size)  
            int where = -1;  
            for (int j = 0; j < b.length; j++) {  
                if (b[j] != -1) {  
                    where++;  
                    if (where == num) {  
                        b[j] = -1;  
                        a[i] = j;  
                    }  
                }  
            }  
            size = size - 1;  
        }  
        // a填满后 将数据加载到rslist  
        StringBuffer ids = new StringBuffer(); 
        for (int i = 0; i < count; i++) {
        	if(ids.length() > 0) {
        		ids.append(",");
        	}
        	ids.append(list.get(a[i]));
        }  
        return ids.toString();  
    }
	
    public static void main(String[] args) throws Exception {
    	releaseArticle();
	}
}

